<template>
	<div class="layout-padding detail-container" v-loading="loading">
		<HyPageHeader class="cursor-pointer" @click="handleBack" :title="title" />
		<div class="page-con">
			<HyCard title="单位信息">
				<HyForm ref="hyFormRef" :hyFormDefault="searchDefault" :hyFormConfig="searchConfig" :hyFormFields="hyFormFields" />
			</HyCard>
			<HyCard title="应用信息">
				<HyForm ref="hyFormRef2" :hyFormDefault="searchDefaultApp" :hyFormConfig="searchConfig" :hyFormFields="hyFormFields2" />
			</HyCard>
			<HyCard title="应用申报依据">
				<el-form :model="basisForm" :rules="basisRules" label-position="right" ref="ruleForm" label-width="240px" class="demo-ruleForm">
					<el-form-item label="请选择要填写应用申报依据类型：" prop="countyReportBase">
						<el-checkbox-group v-model="basisForm.countyReportBase" @change="basisChange">
							<!-- <el-checkbox value="党中央国务院决策部署" label="党中央国务院决策部署" :disabled="checkboxDisabled('党中央国务院决策部署')" name="type"></el-checkbox>
							<el-checkbox value="市委市政府要求" label="市委市政府要求" :disabled="checkboxDisabled('市委市政府要求')" name="type"></el-checkbox>
							<el-checkbox value="群众高频需求" label="群众高频需求" :disabled="checkboxDisabled('群众高频需求')" name="type"></el-checkbox>
							<el-checkbox value="企业共性需求" label="企业共性需求" :disabled="checkboxDisabled('企业共性需求')" name="type"></el-checkbox>
							<el-checkbox value="基层所盼" label="基层所盼" :disabled="checkboxDisabled('基层所盼')" name="type"></el-checkbox>
							<el-checkbox value="先进地区改革创新经验" label="先进地区改革创新经验" :disabled="checkboxDisabled('先进地区改革创新经验')" name="type"></el-checkbox> -->
							<el-checkbox
								v-for="(row, key) in DEMAND_TYPE"
								:value="row.label"
								:label="row.label"
								:disabled="checkboxDisabled(row.label)"
								name="type"
							>
							</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item v-if="basisForm.countyReportBase.includes('党中央国务院决策部署')" label="党中央国务院决策部署：" prop="type2">
						<DecDeploymentCard
							v-for="item in decCardList"
							:key="item.id"
							:id="item.id"
							placeholder="请选择涉及的需求类型"
							text-placeholder="请输入相关指示、批示、文件等对该项工作数字化智能化的具体要求"
							@clickPlus="() => clickPlus(item.type)"
							@clickMinus="() => clickMinus(item.type, item.id)"
							@left-change="(val) => (item.content1 = val)"
							@right-change="(val) => (item.content2 = val)"
							@uploaded="(fileList, id) => uploaded(fileList, id, item.type)"
							:select-options="item.options"
							:show-minus="item.showMinus"
							:select-val="item.content1"
							:text-val="item.content2"
							:fileUrl="item.defaultUrl || ''"
							:fileName="item.defaultName || ''"
						/>
					</el-form-item>
					<el-form-item v-if="basisForm.countyReportBase.includes('市委市政府要求')" label="市委市政府要求：" prop="type2">
						<DecDeploymentCard
							v-for="item in swList"
							:key="item.id"
							:id="item.id"
							@clickPlus="() => clickPlus(item.type)"
							@clickMinus="() => clickMinus(item.type, item.id)"
							@left-change="(val) => (item.content1 = val)"
							@right-change="(val) => (item.content2 = val)"
							@uploaded="(fileList, id) => uploaded(fileList, id, item.type)"
							placeholder="请选择涉及的需求类型"
							text-placeholder="请输入相关指示、批示、文件等对该项工作数字化智能化的具体要求"
							:select-options="item.options"
							:show-minus="item.showMinus"
							:select-val="item.content1"
							:text-val="item.content2"
							:fileUrl="item.defaultUrl || ''"
							:fileName="item.defaultName || ''"
						/>
					</el-form-item>
					<el-form-item v-if="basisForm.countyReportBase.includes('群众高频需求')" label="群众高频需求：" prop="type2">
						<DecDeploymentCard
							v-for="item in qzList"
							:key="item.id"
							:id="item.id"
							@clickPlus="() => clickPlus(item.type)"
							@clickMinus="() => clickMinus(item.type, item.id)"
							@left-change="(val) => (item.content1 = val)"
							@right-change="(val) => (item.content2 = val)"
							@uploaded="(fileList, id) => uploaded(fileList, id, item.type)"
							placeholder="请输入群众反映的高频的、需要从体制机制、流程环节、业务协同等方面解决的问题"
							text-placeholder="请用统计或权威调研数据说明该业务属于高频需求"
							:show-minus="item.showMinus"
							select-type="text"
							:select-val="item.content1"
							:text-val="item.content2"
							:fileUrl="item.defaultUrl || ''"
							:fileName="item.defaultName || ''"
						/>
					</el-form-item>
					<el-form-item v-if="basisForm.countyReportBase.includes('企业共性需求')" label="企业共性需求：" prop="type2">
						<DecDeploymentCard
							v-for="item in qyList"
							:key="item.id"
							:id="item.id"
							@clickPlus="() => clickPlus(item.type)"
							@clickMinus="() => clickMinus(item.type, item.id)"
							@left-change="(val) => (item.content1 = val)"
							@right-change="(val) => (item.content2 = val)"
							@uploaded="(fileList, id) => uploaded(fileList, id, item.type)"
							placeholder="请输入群众反映的高频的、需要从体制机制、流程环节、业务协同等方面解决的问题"
							text-placeholder="请用统计或权威调研数据说明该业务属于企业共性需求"
							:show-minus="item.showMinus"
							select-type="text"
							:select-val="item.content1"
							:text-val="item.content2"
							:fileUrl="item.defaultUrl || ''"
							:fileName="item.defaultName || ''"
						/>
					</el-form-item>
					<el-form-item v-if="basisForm.countyReportBase.includes('基层所盼')" label="基层所盼：" prop="type2">
						<DecDeploymentCard
							v-for="item in jcList"
							:key="item.id"
							:id="item.id"
							@clickPlus="() => clickPlus(item.type)"
							@clickMinus="() => clickMinus(item.type, item.id)"
							@left-change="(val) => (item.content1 = val)"
							@right-change="(val) => (item.content2 = val)"
							@uploaded="(fileList, id) => uploaded(fileList, id, item.type)"
							placeholder="请输入群众反映的高频的、需要从体制机制、流程环节、业务协同等方面解决的问题"
							text-placeholder="请用统计或权威调研数据说明该业务属于基层共性需求"
							:show-minus="item.showMinus"
							select-type="text"
							:select-val="item.content1"
							:text-val="item.content2"
							:fileUrl="item.defaultUrl || ''"
							:fileName="item.defaultName || ''"
						/>
					</el-form-item>
					<el-form-item v-if="basisForm.countyReportBase.includes('先进地区改革创新经验')" label="先进地区改革创新经验：" prop="type2">
						<DecDeploymentCard
							v-for="item in xjList"
							:key="item.id"
							:id="item.id"
							@clickPlus="() => clickPlus(item.type)"
							@clickMinus="() => clickMinus(item.type, item.id)"
							@left-change="(val) => (item.content1 = val)"
							@right-change="(val) => (item.content2 = val)"
							@uploaded="(fileList, id) => uploaded(fileList, id, item.type)"
							placeholder="请选择涉及的需求类型"
							text-placeholder="请对比国家层面推广的先进地区经验案例，找出我市工作中还存在的短板弱项，提出补短板、强弱项的任务"
							:select-options="item.options"
							:show-minus="item.showMinus"
							:select-val="item.content1"
							:text-val="item.content2"
							:fileUrl="item.defaultUrl || ''"
							:fileName="item.defaultName || ''"
						/>
					</el-form-item>
					<el-form-item label="应用概述：" prop="summarize">
						<el-input
							v-model="basisForm.summarize"
							:rows="3"
							show-word-limit
							:maxlength="1000"
							type="textarea"
							placeholder="简述是否做好与“一体化平台'技术规范和管理要求的衔接，是否接入本级数字化城市运行和治理中心，与数字重庆'六大系统”的关系，是否促进基层治理现代化。"
						/>
					</el-form-item>
					<el-form-item label="应用总预算明细">
						<BudgetDetailsTable @table-summaries="tableSummaries" :table-data="tableData" />
					</el-form-item>
					<el-form-item>
						<InfoCard title="网资源信息">
							<el-form-item label="网络资源类型（多选）" prop="netResource" label-width="180">
								<el-cascader
									v-model="basisForm.netResource"
									:options="netWorkOptions"
									:props="networkProps"
									collapse-tags
									collapse-tags-tooltip
									clearable
								/>
							</el-form-item>
						</InfoCard>
					</el-form-item>
					<el-form-item>
						<div class="img-list img-upload__label">
							<el-form-item
								v-for="(item, index) in imgList"
								:key="`${item.propertyName}${index}`"
								:label="item.label"
								label-width="150"
								style="display: block"
								:prop="'item1.' + index + '.url'"
								:rules="{
									required: true,
									validator: (rule, value, callback) => fileMustUpload(rule, value, callback, item),
									trigger: 'change',
								}"
							>
								<upload-img v-model:imageUrl="item.url" v-model:imageName="item.name" :fileSize="200" :file-type="imgFileType">
									<template #empty>
										<el-icon><Plus /></el-icon>
										<span>文件不能大于200MB</span>
									</template>
								</upload-img>
							</el-form-item>
						</div>
					</el-form-item>
					<el-form-item>
						<div class="img-list file-list">
							<el-form-item
								v-for="(item, index) in fileList"
								:key="item.propertyName"
								:label="item.label"
								:label-width="item.labelWidth || '100'"
								style="display: block"
								:prop="'item.' + index + '.url'"
								:rules="{
									required: true,
									validator: (rule, value, callback) => fileMustUpload(rule, value, callback, item),
									trigger: 'change',
								}"
							>
								<span class="file-list-down" @click="downFile">{{ item.downText }}</span>
								<el-upload
									v-model:file-list="item.data"
									class="upload-demo"
									:action="baseURL + '/admin/sys-file/upload'"
									multiple
									:before-upload="(file) => beforeUpload(file, item.accept)"
									:on-success="handleSuccess"
									:on-error="handleError"
									:on-change="validFiles"
									:on-exceed="(files, uploadFiles) => handleExceed(files, uploadFiles, 3)"
									:limit="3"
									:accept="item.accept"
									:headers="headers"
								>
									<el-button type="primary" icon="Upload">上传附件</el-button>
									<template #tip>
										<div class="el-upload__tip">
											{{ item.tips }}
										</div>
									</template>
								</el-upload>
							</el-form-item>
						</div>
					</el-form-item>
				</el-form>
			</HyCard>
		</div>
		<div class="submit-bar">
			<el-button plain :disabled="isDisabled" class="wihte-button" @click="onSave">保存</el-button>
			<el-button plain :disabled="isDisabled" class="blue-button" @click="onSave('申报')">申报</el-button>
		</div>
		<!-- <Start ref="startRef" :boxConfig="{title:'发起流程',width:'40%'}"  @submitPass="submitPass"></Start> -->
	</div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, toRaw } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import HyCard from '/@/components/HyCard/index.vue';
import HyForm from '/@/components/HyForm/index.vue';
import HyPageHeader from '/@/components/HyPageHeader/index.vue';
import DecDeploymentCard from '/@/views/areaDigitalApp/appDeclaration/DecDeploymentCard.vue';
import BudgetDetailsTable from '/@/views/areaDigitalApp/appDeclaration/BudgetDetailsTable.vue';
import InfoCard from '/@/views/areaDigitalApp/appDeclaration/InfoCard.vue';
import { useRouter, useRoute } from 'vue-router';
import { cloneDeep } from 'lodash';
import {
	countyAppDeclare,
	getFlowCode,
	startProcessInstance,
	getAppDecParams,
	upDateCountyAppDeclare,
	getAreaTree,
	getCountyAppDeclare,
	appDeclareApprove,
	appDeclareApproves,
	getLevelList,
	isExsitById,
} from '/@/api/areaDigital';
import { FUND_RESOURCE_NAME, D_BASIS_TYPE } from '/@/views/areaDigitalApp/dictionary';
import { Session } from '/@/utils/storage';
import { downBlobFile } from '/@/utils/other';
import { useDict, useTreeDict } from '/@/hooks/dict';
import mittBus from '/@/utils/mitt';
import { flowName } from '/@/constants';
// import Start from '@cqdcg/admin/views/flow/form/tools/startFlow';
export default defineComponent({
	name: 'index',
	components: {
		HyCard,
		HyForm,
		HyPageHeader,
		InfoCard,
		DecDeploymentCard,
		BudgetDetailsTable,
		// Start
	},
	setup() {
		const title = ref('新增数字化应用备案');
		const router = useRouter();
		const route = useRoute();
		const hyFormRef = ref();
		const hyFormRef2 = ref();
		const ruleForm = ref();
		const loading = ref(false);
		//字典
		const {
			country_lead_dept: COUNTY_LEAD_DEPT,
			belong_domain: APP_DOMAIN,
			fund_resource: FUND_RESOURCE,
			demand_type: DEMAND_TYPE,
			decision_demand_type: DPCC,
			city_government_demand_type: SWSZF,
			reform_demand_type: XJDQGG,
			app_project_type: PROJECTTYPE,
		} = useDict(
			'country_lead_dept',
			'belong_domain',
			'fund_resource',
			'demand_type',
			'decision_demand_type',
			'city_government_demand_type',
			'reform_demand_type',
			'app_project_type'
		);
		const { terminal_area, network_area } = useTreeDict('terminal_area', 'network_area');
		const netWorkOptions = computed(() => {
			return network_area.value;
		});
		const terminalArea = computed(() => {
			return terminal_area.value;
		});
		const startRef = ref();
		const hyFormFields2 = ref({
			//应用信息
			appName: {
				type: 'input',
				label: '数字化应用名称',
				required: true,
			},
			principalName: {
				type: 'input',
				label: '联系人',
				required: true,
			},
			principalPhone: {
				type: 'input',
				label: '联系电话',
				required: true,
				maxlength: 11,
				rules: [
					{ required: true, message: '请输入联系电话', trigger: 'blur' },
					{
						message: '请输入正确的11位手机号',
						pattern: /^1[3-9]\d{9}$/,
						trigger: 'blur',
					},
				],
			},
			projectType: {
				required: true,
				type: 'select',
				label: '应用开发类型',
				options: PROJECTTYPE,
			},
			budgetYear: {
				type: 'date',
				picker: 'year',
				required: true,
				label: '应用预算年度',
				showFormat: 'YYYY',
			},
			developBeginDate: {
				type: 'date',
				picker: 'date',
				required: true,
				label: '应用开发起始时间',
				showFormat: 'YYYY-MM-DD',
				change: (e) => {
					const { developEndDate } = initFormData(hyFormRef2.value.hyForm);
					if (developEndDate) {
						const _start = new Date(e).getTime();
						const _end = new Date(developEndDate).getTime();
						if (_start - _end > 0) {
							hyFormRef2.value.hyForm.developBeginDate = '';
							return ElMessage.error('起始时间不能在终止时间后');
						}
					}
				},
			},
			developEndDate: {
				type: 'date',
				picker: 'date',
				required: true,
				label: '应用开发终止时间',
				showFormat: 'YYYY-MM-DD',
				change: (e) => {
					const { developBeginDate } = initFormData(hyFormRef2.value.hyForm);
					if (developBeginDate) {
						const _end = new Date(e).getTime();
						const _start = new Date(developBeginDate).getTime();
						if (_start - _end > 0) {
							hyFormRef2.value.hyForm.developEndDate = '';
							return ElMessage.error('终止时间不能在起始时间前');
						}
					}
				},
			},
			domain: {
				required: true,
				type: 'select',
				label: '应用领域',
				options: APP_DOMAIN,
			},
			terminal: {
				required: true,
				type: 'cascader',
				label: '应用发布端',
				clearable: true,
				props: { multiple: true },
				options: terminalArea,
			},
			totalBudget: {
				type: 'input',
				label: '应用总投资（万元）',
				disabled: true,
				required: true,
			},
			yearBudget: {
				type: 'inputFunny',
				label: '应用年度预算',
				required: true,
			},
			fundResource: {
				required: true,
				type: 'select',
				label: '资金来源',
				multiple: true,
				collapseTags: true,
				collapseTagsTooltip: true,
				options: FUND_RESOURCE,
				change: (e) => {
					for (let key in FUND_RESOURCE_NAME) {
						if (e.includes(key)) {
							hyFormFields2.value[FUND_RESOURCE_NAME[key]].remove = false;
							hyFormFields2.value.otherFund.remove = key == 6 ? false : true;
						} else {
							hyFormFields2.value[FUND_RESOURCE_NAME[key]].remove = true;
							hyFormRef2.value.hyForm[FUND_RESOURCE_NAME[key]] = '';
							hyFormRef2.value.hyForm.otherFund = '';
						}
					}
				},
			},
			centerAmount: {
				type: 'inputFunny',
				label: '中央财政资金',
				remove: true,
				required: true,
			},
			cityAmount: {
				type: 'inputFunny',
				label: '市级财政资金',
				remove: true,
				required: true,
			},
			districtAmount: {
				type: 'inputFunny',
				label: '区县财政资金',
				remove: true,
				required: true,
			},
			deptAmount: {
				type: 'inputFunny',
				label: '部门财政资金',
				remove: true,
				required: true,
			},
			bankAmount: {
				type: 'inputFunny',
				label: '银行贷款等投资',
				remove: true,
				required: true,
			},
			otherAmount: {
				type: 'inputFunny',
				label: '其它',
				remove: true,
				required: true,
			},
			otherFund: {
				type: 'input',
				label: '其他资金来源名称',
				required: true,
				remove: true,
			},
		});
		const searchConfig = computed(() => {
			return {
				span: 8,
				offset: 0,
				labelWidth: '170px',
				type: 'submit',
			};
		});
		const headers = computed(() => {
			return {
				Authorization: 'Bearer ' + Session.get('token'),
				'TENANT-ID': Session.getTenant(),
			};
		});
		let countyNameName = '';
		const searchDefault = ref({
			countyName: '',
			countyResponsibleDept: '',
			countyBudgetUnit: '',
			countyManageDept: '',
			countyLeadDept: '',
			countyRelevantDept: '',
		});
		const searchDefaultApp = ref({
			appName: '',
			principalName: '',
			principalPhone: '',
			projectType: '',
			budgetYear: '',
			developBeginDate: '',
			developEndDate: '',
			domain: '',
			terminal: '',
			totalBudget: '',
			yearBudget: '',
			fundResource: [],
			centerAmount: '',
			cityAmount: '',
			districtAmount: '',
			deptAmount: '',
			bankAmount: '',
			otherAmount: '',
			otherFund: '',
		});
		const hyFormFields = ref({
			//单位信息
			countyName: {
				type: 'cascader',
				label: '区县名称',
				required: true,
				change(e) {
					console.log(e, initFormData(hyFormRef.value.hyForm));
					hyFormRef.value.hyForm.countyResponsibleDept = '';
					if (e) {
						hyFormFields.value.countyResponsibleDept.disabled = !e;
						let _row = findNodeById(hyFormFields.value.countyName.options, e[e.length - 1]);
						console.log(_row);
						countyNameName = _row?.name;
						getAreaTree({ areaFlag: 2, parentId: e[e.length - 1] }).then((res) => {
							if (res.ok && res.data) {
								res.data.forEach((item) => {
									item['value'] = item.id;
									item['label'] = item.name;
								});
								hyFormFields.value.countyResponsibleDept.options = res.data;
							} else {
								// hyFormFields.value.countyResponsibleDept.disabled = true;
								hyFormFields.value.countyResponsibleDept.options = [];
							}
						});
					} else {
						hyFormFields.value.countyResponsibleDept.disabled = !e;
						countyNameName = '';
					}
				},
				props: {
					value: 'id',
					label: 'name',
				},
				options: [],
			},
			countyResponsibleDept: {
				type: 'select',
				label: '区县责任部门',
				required: true,
				disabled: true,
				props: {
					value: 'id',
					label: 'name',
				},
				options: [],
			},
			countyBudgetUnit: {
				type: 'input',
				label: '区县预算单位',
				required: true,
			},
			countyManageDept: {
				type: 'cascader',
				required: true,
				clearable: true,
				props: {
					multiple: true,
					value: 'deptId',
					label: 'name',
				},
				label: '市级业务主管部门',
				options: [],
			},
			countyLeadDept: {
				// required: true,
				// type: 'select',
				// label: ' 市级牵头部门(专题组组长单位)',
				// // labelWidth:220,
				// options: COUNTY_LEAD_DEPT,
				type: 'cascader',
				label: '市级牵头部门(专题组组长单位)',
				required: true,
				clearable: true,
				props: {
					multiple: true,
					value: 'deptId',
					label: 'name',
				},
				options: [],
			},
			countyRelevantDept: {
				type: 'cascader',
				label: '市级相关部门',
				props: {
					multiple: true,
					value: 'deptId',
					label: 'name',
				},
				options: [],
			},
		});
		const basisForm = ref({
			countyReportBase: ['党中央国务院决策部署'],
			summarize: '',
			netResource: [],
		});
		const basisRules = ref({
			countyReportBase: [{ type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }],
			summarize: [{ required: true, message: '请输入必填项', trigger: 'blur' }],
			netResource: [{ required: true, message: '请选择必填项', trigger: 'change' }],
		});
		const networkProps = { multiple: true };
		const imgFileType = ['image/jpeg', 'image/png'];
		const imgList = ref([
			{
				type: 1,
				propertyName: 'name1',
				label: '总体业务架构图',
				url: '',
				name: '',
			},
			{
				type: 2,
				propertyName: 'name2',
				label: '系统架构图',
				url: '',
				name: '',
			},
			{
				type: 7,
				propertyName: 'name3',
				label: '数据流向图',
				url: '',
				name: '',
			},
			{
				type: 8,
				propertyName: 'name4',
				label: '网络拓扑图',
				url: '',
				name: '',
			},
		]);
		const fileList = ref([
			{
				propertyName: 'file1',
				label: '正式书面函',
				tips: '仅支持上传pdf/jpg格式文件，文件不能超过200MB',
				data: [],
				accept: '.pdf,.jpg',
				type: 11,
			},
			{
				propertyName: 'file2',
				label: `资金计划报告（上传资金计划报告）`,
				labelWidth: '250',
				downText: '模板下载',
				tips: '仅支持上传doc/docx/pdf/jpg格式文件，文件不能超过200MB',
				data: [],
				accept: '.doc,.docx,.pdf,.jpg',
				type: 10,
			},
			{
				type: 12,
				propertyName: 'file3',
				label: '相关佐证材料',
				labelWidth: '110',
				tips: '仅支持上传rar/zip/doc/docx/pdf/jpg格式文件，文件不能超过200MB',
				data: [],
				accept: '.rar,.zip,.doc,.docx,.pdf,.jpg',
			},
		]);
		const decCardList = ref([
			{
				id: -1,
				showMinus: false,
				options: DPCC,
				type: '1',
				content1: '', // 内容或者涉及的需求类型
				content2: '', // 相关指示
				fileUrl: '',
				fileName: '',
			},
		]);
		const swList = ref([
			{
				id: -1,
				showMinus: false,
				options: SWSZF,
				type: '2',
				content1: '', // 内容或者涉及的需求类型
				content2: '', // 相关指示
				fileUrl: '',
				fileName: '',
			},
		]);
		const qzList = ref([
			{
				id: -1,
				showMinus: false,
				type: '3',
				content1: '', // 内容或者涉及的需求类型
				content2: '', // 相关指示
				fileUrl: '',
				fileName: '',
			},
		]);
		const qyList = ref([
			{
				id: -1,
				showMinus: false,
				type: '4',
				content1: '', // 内容或者涉及的需求类型
				content2: '', // 相关指示
				fileUrl: '',
				fileName: '',
			},
		]);
		const jcList = ref([
			{
				id: -1,
				showMinus: false,
				type: '5',
				content1: '', // 内容或者涉及的需求类型
				content2: '', // 相关指示
				fileUrl: '',
				fileName: '',
			},
		]);
		const xjList = ref([
			{
				id: -1,
				showMinus: false,
				options: XJDQGG,
				type: '6',
				content1: '', // 内容或者涉及的需求类型
				content2: '', // 相关指示
				fileUrl: '',
				fileName: '',
			},
		]);
		const types = {
			'1': decCardList, // 党中央国务院决策部署
			'2': swList, // 市委市政府要求
			'3': qzList, // 群众高频需求
			'4': qyList, // 企业共性需求
			'5': jcList, // 基层所盼
			'6': xjList, // 先进地区改革创新经验
		};
		const optionsTypes = {
			'1': DPCC, // 党中央国务院决策部署
			'2': SWSZF, // 市委市政府要求
			'6': XJDQGG, // 先进地区改革创新经验
		};
		const tableData = ref([
			{
				numIdx: '1',
				parentNumIdx: '0',
				name: '应用建设费用',
				amount: null,
				remark: '',
				children: [
					{ numIdx: '1.1', parentNumIdx: '1', name: '软件购置费用', amount: null, remark: '' },
					{ numIdx: '1.2', parentNumIdx: '1', name: '数治理费用', amount: null, remark: '' },
					{ numIdx: '1.3', parentNumIdx: '1', name: '标准规范编制费用', amount: null, remark: '' },
					{ numIdx: '1.4', parentNumIdx: '1', name: '租用费用', amount: null, remark: '' },
					{ numIdx: '1.5', parentNumIdx: '1', name: '集成费用', amount: null, remark: '' },
				],
			},
			{
				numIdx: '2',
				parentNumIdx: '0',
				name: '应用建设其他费用',
				amount: null,
				remark: '',
				children: [
					{ numIdx: '2.1', parentNumIdx: '2', name: '初步设计费', amount: null, remark: '' },
					{ numIdx: '2.2', parentNumIdx: '2', name: '工程监理费', amount: null, remark: '' },
					{ numIdx: '2.3', parentNumIdx: '2', name: '安全风险评估及等保测评费', amount: null, remark: '' },
				],
			},
			{
				numIdx: '3',
				parentNumIdx: '0',
				name: '网资源费用',
				amount: null,
				remark: '',
			},
			{
				numIdx: '4',
				parentNumIdx: '0',
				name: '政务云资源费用',
				amount: null,
				remark: '',
			},
			{
				numIdx: '5',
				parentNumIdx: '0',
				name: '能力组件费用',
				amount: null,
				remark: '',
			},
		]);
		function handleBack() {
			router.push({ name: '数字化应用备案申报' });
		}
		//控制按钮
		const isDisabled = ref(false);
		//文件上传成功
		function handleSuccess() {
			isDisabled.value = false;
		}
		function handleError() {
			isDisabled.value = false;
		}
		function beforeUpload(file, accept) {
			//上传验证
			const { size, type } = file;
			const fileType = accept.split(',');
			// const fileType = []
			if (fileType.length) {
				const fileName = file.name.split('.');
				const fileExt = `.${fileName[fileName.length - 1]}`;
				const isTypeOk = fileType.includes(fileExt);
				if (!isTypeOk) {
					ElMessage.error(`文件格式错误，请上传 ${fileType.join(',')} 格式的文件`);
					return false;
				}
			}
			const maxSize = 1024 * 1024 * 200; // 例如，限制为 200MB
			if (size > maxSize) {
				ElMessage.error('文件大小超过限制，请选择小于 200MB 的文件');
				return false;
			}
			isDisabled.value = true;
			return true;
		}
		function clickPlus(type) {
			//加
			const len = types[type].value.length;
			console.log(types[type].value[len - 1]);
			types[type].value.push({
				id: len + 1,
				type,
				showMinus: len > 0,
				options: types[type].value[len - 1].options,
				content1: '',
				content2: '',
				fileUrl: '',
				fileName: '',
			});
		}
		function clickMinus(type, id) {
			//减
			const index = types[type].value.findIndex((item) => item.id === id);
			if (index > -1) {
				types[type].value.splice(index, 1);
			}
		}
		function basisChange(e) {
			// console.log(e)
		}
		function checkboxDisabled(label) {
			if (basisForm.value.countyReportBase.length < 2 && basisForm.value.countyReportBase.includes(label)) {
				return true;
			}
			return false;
		}
		function initListData(list) {
			const arr = cloneDeep(list);
			return arr.map((item) => {
				// console.log(item)
				delete item.id;
				delete item.showMinus;
				delete item.options;
				delete item.defaultUrl;
				delete item.defaultName;
				return item;
			});
		}
		function checkList() {
			//解析申报依据类型数据
			const checkArr = [];
			basisForm.value.countyReportBase.forEach((item) => {
				console.log(initListData(types[D_BASIS_TYPE[item]].value));
				checkArr.push(initListData(types[D_BASIS_TYPE[item]].value));
			});
			return checkArr.flat();
		}
		function initFormData(form) {
			//处理表单内容
			form = toRaw(form);
			const obj = {};
			for (const key in form) {
				let val = form[key];
				if (Array.isArray(val)) {
					obj[key] = val.join(',');
				} else {
					obj[key] = val;
				}
			}
			return obj;
		}
		function uploaded(fileList, id, type) {
			//文件上传回调
			console.log(id, type);
			const arr = toRaw(fileList.value);
			console.log(arr, '---------');
			let data = [];
			arr.forEach((item) => {
				if (item.url) {
					data.push(item);
				}
				if (item.response?.ok) {
					item.response.data.name = item.name;
					data.push(item.response.data);
				}
			});
			console.log(data);
			let _index = types[type].value.findIndex((item) => item.id == id);
			types[type].value[_index].fileUrl = data.map((item) => item.url).join(',');
			types[type].value[_index].fileName = data.map((item) => item.name).join(',');
			console.log(types[type].value, _index);
		}
		function formatFileList() {
			//提交前处理文件
			let arr = [];
			const _arr = toRaw(imgList.value);
			_arr.forEach((item) => {
				let row = JSON.parse(JSON.stringify(item));
				delete row.label;
				delete row.propertyName;
				if (row.url) arr.push(row);
			});
			fileList.value.forEach((item) => {
				item.data.forEach((i) => {
					if (i.fileId) {
						let json = {
							type: i.type,
							name: i.name,
							url: i.url,
						};
						arr.push(json);
					} else if (i.response && i.response.ok) {
						let json = {
							type: item.type,
							name: i.name || i.response.data?.name,
							url: i.response.data?.url,
						};
						arr.push(json);
					}
				});
			});
			// console.log(arr)
			return arr;
		}
		function fileMustUpload(rule, value, callback, item) {
			//申报依据文件验证
			if (item.hasOwnProperty('url') && item.url.length === 0) {
				return callback(new Error(`请上传${item.label}`));
			} else if (item.hasOwnProperty('data') && item.data.length === 0) {
				return callback(new Error(`请上传${item.label}`));
			} else {
				return callback();
			}
		}
		function validFiles() {
			//验证文件上传
			ruleForm.value.validate();
		}
		function formatTable(arr: Array<{ [key: string]: any }>, pIdx: string | number) {
			//提交前表格排序
			for (let i = 1; i <= arr.length; i++) {
				let item = arr[i - 1];
				item.amount = item.amount || 0;
				if (pIdx == 0) {
					item.numIdx = i;
				} else {
					item.numIdx = pIdx + '.' + i;
				}
				item.parentNumIdx = pIdx;
				if (item.children) {
					item.children = formatTable(item.children, item.numIdx);
				}
			}
			return arr;
		}
		async function onSave(type: string) {
			//保存前验证
			// console.log(fileList.value,imgList.value,basisForm.value)
			// ruleForm.value.validate((valid)=>{
			// 	console.log(valid)
			// })
			// 点击【保存】，保存当前内容，返回【数字化应用备案申报-列表】，状态为【待申报】
			const arr = [hyFormRef.value.check(), hyFormRef2.value.check()];
			const checked = await Promise.all(arr);

			if (checked.every((item) => Boolean(item))) {
				ruleForm.value.validate((valid, err) => {
					console.log(basisForm.value);
					if (valid) {
						let queryForm: any = {};
						const infoForm = initFormData(hyFormRef.value.hyForm);
						const infoFormApp = initFormData(hyFormRef2.value.hyForm);
						infoFormApp.terminal = infoFormApp.terminal
							.split(',')
							.filter((i) => i != 99)
							.join(',');
						const basForm = cloneDeep(toRaw(basisForm.value));
						const declareBaseEntityList = checkList(); // 解析申报依据类型数据
						try {
							declareBaseEntityList.forEach((item) => {
								// console.log(item)
								let name;
								for (let key in D_BASIS_TYPE) {
									if (D_BASIS_TYPE[key] == item.type) name = key;
								}
								if (!item.content1 || !item.content2) {
									ElMessage.error(`请填写完全${name}的相关内容`);
									throw new Error();
								}
								if (!item.fileUrl) {
									ElMessage.error(`请上传${name}的佐证材料`);
									throw new Error();
								}
							});
						} catch (err) {
							return false;
						}
						// let len = declareBaseEntityList.filter(item=>!item.fileUrl)
						// if(len.length>0){
						// 	return ElMessage.error('请上传申报依据佐证材料')
						// }
						basForm.countyReportBase = basForm.countyReportBase.map((item) => D_BASIS_TYPE[item]).join(',');
						const _tableData = JSON.parse(JSON.stringify(toRaw(tableData.value)));
						const tableRes = formatTable(_tableData, 0); // 解析表格数据
						// 解析网络资源类型
						const _netWork = basisForm.value.netResource.map((item) => {
							if (item.length > 1) {
								return item[item.length - 1];
							} else {
								return item;
							}
						});
						const netWork = _netWork.join(',');
						const declareFileList = formatFileList();
						queryForm = {
							...infoForm,
							...infoFormApp,
							...basForm,
							countyNameName,
							netResource: netWork,
							declareBaseEntityList,
							declareBudgetVoList: tableRes,
							declareFileList,
						};
						queryForm.countyName = queryForm.countyName.split(',')[queryForm.countyName.split(',').length - 1];
						delete queryForm.__v_isRef;
						delete queryForm.__v_isShallow;
						delete queryForm.dep;
						delete queryForm._rawValue;
						delete queryForm._value;
						console.log(queryForm, '----');
						if (type == '申报') {
							ElMessageBox.confirm('是否确认提交申报？', '申报确认', {
								confirmButtonText: '确认',
								cancelButtonText: '取消',
								type: 'warning',
							})
								.then(() => {
									handleSubmit(queryForm, '申报');
									// onSave('申报');
								})
								.catch(() => {});
						} else {
							handleSubmit(queryForm, '');
						}
					}
				});
			}
		}
		function handleSubmit(queryForm: any, type: string) {
			//提交
			loading.value = true;
			if (route.query.id && countryApproveStatus.value != 4) {
				//不通过（4）调用保存新增接口
				isExsitById({
					declareId: route.query.id,
				})
					.then((_res) => {
						if (_res.ok) {
							if (_res.data) {
								queryForm.declareId = route.query.id;
								upDateCountyAppDeclare(queryForm)
									.then((res) => {
										if (res.ok) {
											if (type == '申报') {
												declareApp();
											} else {
												loading.value = false;
												ElMessage.success('操作成功');
											}
										} else {
											loading.value = false;
											ElMessage.error(res.msg);
										}
									})
									.catch(() => {
										loading.value = false;
									});
							} else {
								loading.value = false;
								ElMessage.error('该数据已被删除');
								setTimeout(() => {
									mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
								}, 200);
							}
						} else {
							ElMessage.error(_res.msg);
							loading.value = false;
						}
					})
					.catch(() => {
						loading.value = false;
					});
			} else {
				if (countryApproveStatus.value == 4) {
					delete queryForm.declareId;
					queryForm['appCode'] = route.query.appCode;
				}
				countyAppDeclare(queryForm)
					.then((res) => {
						console.log(res, '------------');
						if (res.ok) {
							startProcess(res.data, type);
						} else {
							loading.value = false;
							ElMessage.error(res.msg);
						}
					})
					.catch(() => {
						loading.value = false;
					});
			}
		}
		function startProcess(data: any, type: string) {
			try {
				console.log(data, type);
				let parmas = {
					businessKey: data.declareId,
					flowName: flowName.AREADIGITAL,
				};
				startProcessInstance(parmas).then((res) => {
					if (res.ok) {
						if (type == '申报') {
							declareApp(res.data.processInstanceId);
						} else {
							loading.value = false;
							ElMessage.success('操作成功');
							mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
							router.push('/areaDigitalApp/filings/index');
						}
					} else {
						loading.value = false;
						ElMessage.error(res.msg);
					}
				});
			} catch (error) {
				loading.value = false;
			}
		}

		function declareApp(processInstanceId = '', nodeId = '', taskId = '', appCode = '') {
			//申报
			appDeclareApproves({
				processInstanceId: processInstanceId || route.query.processInstanceId,
				paramMap: {
					operation: 'pass',
				},
			})
				.then((res) => {
					if (res.ok) {
						ElMessage.success('操作成功');
						setTimeout(() => {
							mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
							router.push('/areaDigitalApp/filings/index');
						}, 300);
					} else {
						ElMessage.error(res.msg);
					}
				})
				.finally(() => {
					loading.value = false;
				});
		}
		function submitPass() {
			ElMessage.success('提交成功');
		}

		function tableSummaries(sum) {
			// const data = cloneDeep(searchDefaultApp);
			// searchDefaultApp.value = {
			// 	...data,
			// 	totalBudget: sum,
			// };
			setTimeout(() => {
				hyFormRef2.value.hyForm.totalBudget = sum;
			}, 0);
			// searchDefaultApp.value.totalBudget = sum;
		}
		function downFile() {
			//下载
			downBlobFile('/admin/sys-file/local/file/重庆市政务数字化应用资金计划报告（模板）.docx', {}, '重庆市政务数字化应用资金计划报告（模板）.docx');
		}
		function findNodeById(treeData, nodeId) {
			//区县下拉
			// 遍历当前层级的所有节点
			for (let i = 0; i < treeData.length; i++) {
				let node = treeData[i]; // 如果当前节点的 ID 匹配目标节点的 ID，则返回当前节点
				if (node.id === nodeId) {
					return node;
				} // 如果当前节点有子节点，则递归调用当前函数继续查找子节点
				if (node.children && node.children.length > 0) {
					let foundNode = findNodeById(node.children, nodeId); // 如果在子节点中找到了目标节点，则返回找到的节点
					if (foundNode) {
						return foundNode;
					}
				}
			}
			// 如果遍历完所有节点仍未找到目标节点，则返回 null
			return null;
		}
		onMounted(() => {
			if (route.query?.id) {
				title.value = '编辑数字化应用备案';
				getDetailData(route.query.id);
			}
			//区县名称
			getAreaTree({ areaFlag: 1 }).then((res) => {
				if (res.ok) {
					hyFormFields.value.countyName.options = res.data;
				}
			});
			//市级业务主管部门 and 市级相关部门
			getLevelList({ level: 2 }).then((res) => {
				console.log(res, '部门------');
				if (res.ok) {
					hyFormFields.value.countyManageDept.options = res.data;
					hyFormFields.value.countyRelevantDept.options = res.data;
					hyFormFields.value.countyLeadDept.options = res.data;
				}
			});
		});
		//应用信息数据
		const _appData = {
			appName: '',
			principalName: '',
			principalPhone: '',
			projectType: '',
			budgetYear: '',
			developBeginDate: '',
			developEndDate: '',
			domain: '',
			terminal: '',
			totalBudget: '',
			yearBudget: '',
			fundResource: [],
			centerAmount: '',
			cityAmount: '',
			districtAmount: '',
			deptAmount: '',
			bankAmount: '',
			otherAmount: '',
			otherFund: '',
		};
		let countryApproveStatus = ref(0);
		function getDetailData(id: Number) {
			//详情
			loading.value = true;
			getCountyAppDeclare(id)
				.then((res) => {
					if (res.ok) {
						console.log(res.data);
						countryApproveStatus.value = res.data.countryApproveStatus; //不通过（4）调用保存新增接口
						for (let key in _appData) {
							if (key == 'terminal') {
								_appData[key] = res.data[key] && res.data[key].split(',').map((item) => item && item);
							} else if (key == 'fundResource') {
								_appData[key] = res.data[key] && res.data[key].split(',');
								for (let val in FUND_RESOURCE_NAME) {
									if (_appData[key].includes(val)) {
										hyFormFields2.value[FUND_RESOURCE_NAME[val]].remove = false;
										hyFormFields2.value.otherFund.remove = val == 6 ? false : true;
									}
								}
							} else {
								_appData[key] = res.data[key];
							}
						}
						searchDefaultApp.value = _appData;
						// for (let key in searchDefaultApp.value) {
						// 	searchDefaultApp.value[key] = res.data[key];
						// }
						for (let key in searchDefault.value) {
							if (key == 'countyManageDept' || key == 'countyRelevantDept' || key == 'countyLeadDept') {
								searchDefault.value[key] = res.data[key] && res.data[key].split(',');
							} else {
								searchDefault.value[key] = res.data[key];
							}
						}
						if (searchDefault.value.countyName) {
							console.log(searchDefault.value.countyName, '111111111111s');
							getAreaTree({ areaFlag: 2, parentId: searchDefault.value.countyName }).then((res) => {
								if (res.ok && res.data) {
									res.data.forEach((item) => {
										item['value'] = item.id;
										item['label'] = item.name;
									});
									hyFormFields.value.countyResponsibleDept.options = res.data;
								}
							});
							hyFormFields.value.countyResponsibleDept.disabled = false;
						}
						basisForm.value.countyReportBase = [];
						console.log(res.data.countyReportBase.split(','), '------------');
						res.data.countyReportBase &&
							res.data.countyReportBase.split(',').forEach((item) => {
								//应用申报依据
								for (let i in D_BASIS_TYPE) {
									if (D_BASIS_TYPE[i] == item && !basisForm.value.countyReportBase.includes(i)) {
										basisForm.value.countyReportBase.push(i);
									}
								}
								//
								types[item].value = [];
								res.data.declareBaseEntityList.forEach((row) => {
									if (row.type == item) {
										let len = types[item].value.length + 1;
										row['id'] = len;
										row['defaultUrl'] = row.fileUrl;
										row['defaultName'] = row.fileName;
										row['showMinus'] = false;
										if (optionsTypes.hasOwnProperty(item)) {
											row['options'] = optionsTypes[item];
										}
										types[item].value.push(row);
									}
								});
							});
						basisForm.value.summarize = res.data.summarize;
						// basisForm.value.netResource = res.data.netResource
						basisForm.value.netResource = res.data.netResource.split(',').map((item) => item);
						tableData.value = res.data.declareBudgetVoList;
						countyNameName = res.data.countyNameName;
						//文件
						res.data.declareFileList.forEach((item) => {
							imgList.value.forEach((img) => {
								if (item.type == img.type) {
									img.url = item.url;
									img.name = item.name;
								}
							});
							fileList.value.forEach((file) => {
								if (item.type == file.type) {
									file.data.push(item);
								}
							});
						});
					} else {
						ElMessage.error(res.msg);
					}
				})
				.finally(() => {
					loading.value = false;
				});
		}
		function handleExceed(files, uploadFiles, limit) {
			ElMessage.warning(`最多上传${limit}个文件!`);
		}
		return {
			startRef,
			DEMAND_TYPE,
			countryApproveStatus,
			title,
			loading,
			hyFormFields,
			hyFormFields2,
			searchConfig,
			searchDefault,
			searchDefaultApp,
			netWorkOptions,
			networkProps,
			basisForm,
			basisRules,
			imgFileType,
			imgList,
			fileList,
			decCardList,
			swList,
			qzList,
			qyList,
			jcList,
			xjList,
			hyFormRef,
			hyFormRef2,
			ruleForm,
			tableData,
			headers,
			handleExceed,
			beforeUpload,
			validFiles,
			uploaded,
			clickPlus,
			clickMinus,
			checkboxDisabled,
			handleBack,
			onSave,
			basisChange,
			tableSummaries,
			downFile,
			fileMustUpload,
			findNodeById,
			submitPass,
			handleSuccess,
			handleError,
			isDisabled,
		};
	},
});
</script>

<style scoped lang="scss">
.detail-container {
	height: auto;
	.page-con {
		height: calc(100vh - 236px);
		overflow-y: auto;
		display: flex;
		flex-direction: column;
		gap: 10px;
	}
	.img-list {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 20px;
		width: 100%;
	}
	.file-list {
		position: relative;
		> div {
			width: 33%;
			max-width: 330px;
			flex-shrink: 0;
		}
		.file-list-down {
			position: absolute;
			top: -32px;
			right: 22px;
			cursor: pointer;
			color: #409eff;
		}
	}
	.submit-bar {
		width: 100%;
		padding: 10px;
		box-sizing: border-box;
		background-color: #fff;
		text-align: center;
		margin-top: 5px;
		box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
	}
}

:deep(.img-upload__label .el-form-item__label) {
	justify-content: center;
}
.img-list {
	:deep(.is-success) {
		max-width: 70%;
		overflow: hidden;
	}
}
</style>
